import Taro from "@tarojs/taro";
import React, { useEffect, useState } from "react";

const OFFSET_DIRECTION_ALL = 'all';
const OFFSET_DIRECTION_LEFT = 'left';
const OFFSET_DIRECTION_RIGHT = 'right';
const OFFSET_DIRECTION_LEFT_LIST = [OFFSET_DIRECTION_ALL, OFFSET_DIRECTION_LEFT];
const OFFSET_DIRECTION_RIGHT_LIST = [OFFSET_DIRECTION_ALL, OFFSET_DIRECTION_RIGHT];

function useMsgActionPup(props: IMsgActionPup) {
  const { pupData = {}, offset, handleClick } = props;
  const { direction = '', distance = '' } = offset || {};
  const [winSize, setWinSize] = useState<{
    height: number;
    width: number;
  }>({ height: 0, width: 0 });
  const [popStyle, setPopStyle] = useState("");
  const [show, setShow] = useState(false);
  // 当前点击的位置出现的 操作按钮的 箭头是上面还是下面
  const [upTarget, setUpTarget] = useState(true);

  const handelPupData = (data = {}) => {
    console.log("handelPupData", data);
    console.log("handelPupData winSize", winSize);
    const { event = {} } = data;
    const touches = event?.touches?.[0] ?? {};
    let style = "";
    if (touches.clientY > winSize.height / 2) {
      setUpTarget(false);
      style = `bottom:${winSize.height - touches.clientY}px;`;
    } else {
      setUpTarget(true);
      style = `top:${touches.clientY}px;`;
    }
    if (touches.clientX > winSize.width / 2) {
      // 展示再右边
      if (OFFSET_DIRECTION_RIGHT_LIST.includes(direction)) {
        style += `right:calc(32rpx + ${distance})`;
      } else {
        style += `right:32rpx`;
      }
    } else {
      // 展示再左边
      if (OFFSET_DIRECTION_LEFT_LIST.includes(direction)) {
        style += `left:calc(32rpx + ${distance})`;
      } else {
        style += `right:32rpx`;
      }
    }
    console.log("style", style);
    setPopStyle(style);
    setShow(true);
  };

  const getWindowSize = () => {
    Taro.getSystemInfo({
      success: (res) => {
        setWinSize({
          width: res.windowWidth,
          height: res.windowHeight,
        });
      },
    });
  };

  const closePup = () => {
    console.log("closePup");
    if (show) {
      setShow(false);
    }
  };
  const cancelPup = (e) => {
    e.stopPropagation();
    setShow(false);
  };

  const handleActionClick = (item: IMsgActionItem) => {
    console.log("handleClick item", item);
    handleClick?.(item)

  };

  useEffect(() => {
    if (pupData.event) {
      handelPupData(pupData);
    }
  }, [pupData]);

  useEffect(() => {
    getWindowSize();
  }, []);
  return {
    show,
    popStyle,
    upTarget,
    closePup,
    cancelPup,
    handleActionClick,
  };
}

export default useMsgActionPup;
